
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { addHistory, removeHistory, clearHistory } from '../store/searchSlice';
import { ArrowLeft, Search, Trash2, Building2, Pill, Stethoscope, User, FileText } from 'lucide-react';
import request from '../api/request';


interface SearchResult {
	id: string;
	name: string;
	type: 'doctor' | 'hospital' | 'medicine' | 'symptom' | 'article';
	description?: string;
	image?: string;
	author?: string;
	price?: string;
	rating?: string;
	views?: string;
}

type SearchTab = 'comprehensive' | 'article' | 'doctor' | 'hospital' | 'medicine';

const synonymMap: Record<string, string[]> = {
	'感冒': ['呼吸', '内科', '全科', '感染', '耳鼻喉', '咳嗽', '发热', '发烧', '上呼吸道'],
	'咳嗽': ['呼吸', '内科', '感染', '耳鼻喉', '哮喘', '支气管'],
	'发烧': ['感染', '内科', '全科', '呼吸'],
	'头痛': ['神经', '内科', '全科', '偏头痛', '紧张性头痛'],
	'腹痛': ['消化', '内科', '外科', '胃肠', '肝胆'],
	'高血压': ['心内', '内科', '心血管', '血压'],
	'糖尿病': ['内分泌', '内科', '代谢', '血糖'],
};

const norm = (s: string) => (s || '').toLowerCase().replace(/\s+/g, '');

/**
 * 搜索页面组件 - 综合搜索功能
 * 
 * 功能特性：
 * - 多类型内容搜索（医生、医院、药品、症状、文章）
 * - 搜索历史记录管理
 * - 同义词搜索支持
 * - 标签页分类搜索
 * - 实时搜索结果展示
 * - 智能关键词匹配
 * 
 * 主要状态：
 * - value: 搜索关键词
 * - loading: 搜索加载状态
 * - results: 搜索结果列表
 * - error: 错误信息
 * - activeTab: 当前激活的搜索标签页
 * 
 * 搜索类型：
 * - comprehensive: 综合搜索
 * - article: 文章搜索
 * - doctor: 医生搜索
 * - hospital: 医院搜索
 * - medicine: 药品搜索
 * 
 * 同义词映射：
 * - 支持常见症状的同义词搜索
 * - 自动扩展搜索范围
 * 
 * API接口：
 * - GET /doctor/list - 医生搜索
 * - GET /hospital/list - 医院搜索
 * - GET /medicine/list - 药品搜索
 * - GET /article/list - 文章搜索
 * 
 * @returns {JSX.Element} 搜索页面组件
 */
export default function SearchPage() {
	const navigate = useNavigate();
	const dispatch = useAppDispatch();
	const history = useAppSelector((s) => s.search.history);
	const [value, setValue] = useState('');
	const [loading, setLoading] = useState(false);
	const [results, setResults] = useState<SearchResult[]>([]);
	const [error, setError] = useState<string | null>(null);
	const [activeTab, setActiveTab] = useState<SearchTab>('comprehensive');


	const doSearch = async (keyword?: string) => {
		const raw = (keyword ?? value).trim();
		if (!raw) return;
		setError(null);
		setLoading(true);
		setResults([]);
		
		try {
			dispatch(addHistory(raw));
			const allResults: SearchResult[] = [];
			
			// 根据当前选中的标签进行搜索
			if (activeTab === 'comprehensive' || activeTab === 'doctor') {
				// 1. 搜索医生
				try {
					const resp = await request.get('/doctor/list', {
						params: { pageCode: '1', pageSize: '100' },
					});
					const list: any[] = resp?.data?.data || [];
					console.log('医生API原始数据:', list);
					
					const normalized = list.map((item, index) => ({
						id: String(item.doctorid || item.id || `doc_${index}`),
						name: String(item.doctorname || item.name || '未知医生'),
						title: String(item.doctorstate || item.title || '医生'),
						department: String(item.socoadmin || item.doctoradministre || item.department || ''),
						specialties: String(item.doctordescword || item.specialties || item.specialty || ''),
						hospital: String(item.nosocomium || item.hospital || ''),
						avatar: item.doctorimage || item.avatar,
						rating: item.doctorgood || '99%',
						views: item.doctorbrowse || '0',
						price: item.doctorprice || '100',
					}));

					const q = norm(raw).replace(/科/g, '');
					const match = (d: any) => {
						const fields = [d.name, d.title, d.department, d.specialties, d.hospital]
							.map((x) => norm(String(x)).replace(/科/g, ''));
						return fields.some((f) => f.includes(q));
					};

					let filtered = normalized.filter(match);

					// 如果没有直接命中，尝试同义关键词  
					if (filtered.length === 0 && synonymMap[raw]) {
						const keys = synonymMap[raw].map((k) => norm(k));
						filtered = normalized.filter((d) => {
							const fields = [d.name, d.title, d.department, d.specialties, d.hospital]
								.map((x) => norm(String(x)).replace(/科/g, ''));0
							return fields.some((f) => keys.some((k) => f.includes(k)));
						});
					}

					// 限制医生结果数量
					filtered = filtered.slice(0, 10);

					const doctorResults: SearchResult[] = filtered.map((d) => ({
						id: d.id,
						name: `${d.name} ${d.title}`.trim(),
						type: 'doctor',
						description: [d.hospital, d.department, d.specialties && `擅长：${d.specialties}`]
							.filter(Boolean)
							.join(' '),
						image: d.avatar,
						author: d.hospital,
						price: `¥${d.price}起`,
						rating: d.rating,
						views: d.views,
					}));
					allResults.push(...doctorResults);
					console.log('医生搜索结果:', doctorResults);
				} catch (e) {
					console.warn('医生搜索失败:', e);
				}
			}

			if (activeTab === 'comprehensive' || activeTab === 'hospital') {
				// 2. 搜索医院
				try {
					console.log('开始搜索医院，关键词:', raw);
					
					// 构建医院搜索参数 - 先尝试不传搜索参数
					const hospitalParams: any = { 
						pageCode: '1', 
						pageSize: '20'

						
					};
					
					// 如果API支持搜索，再添加搜索参数
					// if (raw) {
					// 	hospitalParams.search = raw;
					// 	hospitalParams.keyword = raw;
					// 	hospitalParams.name = raw;
					// }
					
					const hospitalResp = await request.get('/nosocomium/list', {
						params: hospitalParams,
					});
					
					console.log('医院API完整响应:', hospitalResp);
					console.log('医院API数据结构:', {
						data: hospitalResp?.data,
						dataData: hospitalResp?.data?.data,
						type: typeof hospitalResp?.data?.data,
						length: Array.isArray(hospitalResp?.data?.data) ? hospitalResp?.data?.data.length : 'not array'
					});
					const hospitalList: any[] = hospitalResp?.data?.data || [];
					
					if (hospitalList.length > 0) {
						console.log('找到医院数据:', hospitalList.length, '条');
						console.log('第一条医院数据:', hospitalList[0]);
						
						const hospitalResults: SearchResult[] = hospitalList
							.slice(0, 5)
							.map((item, index) => {
								// 使用正确的字段名
								const hospitalName = item.nosocomium || item.name || item.hospitalname || item.hospital_name || `医院${index + 1}`;
								const level = item.socolv || item.lv || item.level || item.hospitallevel || item.grade || '医院';
								const city = item.sococity || item.city || item.location || item.address || '未知城市';
								const state = item.socostate || item.state || item.type || item.hospitaltype || '医院类型';
								const admin = item.socoadmin || item.admin || item.department || item.specialty || '知名科室';
								
								return {
									id: String(item.socoid || item.id || item.hospitalid || `hosp_${index}`),
									name: hospitalName,
									type: 'hospital',
									description: `${level} | ${city} | ${state} | ${admin}`,
									image: item.socoimage || item.image || item.hospitalimage || item.picture,
									author: city,
									rating: item.rating || '4.5',
									views: item.views || '0',
								};
							});
						allResults.push(...hospitalResults);
						console.log('处理后的医院结果:', hospitalResults);
					} else {
						console.log('医院API返回空数据');
					}
				} catch (e) {
					console.warn('医院搜索失败:', e);
					console.log('错误详情:', {
						message: e.message,
						status: e.response?.status,
						statusText: e.response?.statusText,
						url: e.config?.url,
						params: e.config?.params
					});
				}
			}

			if (activeTab === 'comprehensive' || activeTab === 'medicine') {
				// 3. 搜索药品 - 使用真实API
				try {
					console.log('开始搜索药品，关键词:', raw);
					const medicineResp = await request.get('/restorative/list', {
						params: { 
							pageCode: '1', 
							pageSize: '20',
							search: raw 
						},
					});
					
					console.log('药品API完整响应:', medicineResp);
					console.log('药品API数据结构:', {
						data: medicineResp?.data,
						dataData: medicineResp?.data?.data,
						type: typeof medicineResp?.data?.data,
						length: Array.isArray(medicineResp?.data?.data) ? medicineResp?.data?.data.length : 'not array'
					});
					
					const medicineList: any[] = medicineResp?.data?.data || [];
					if (medicineList.length > 0) {
						console.log('找到药品数据:', medicineList.length, '条');
						console.log('第一条药品数据:', medicineList[0]);
						
						const medicineResults: SearchResult[] = medicineList
							.slice(0, 5)
							.map((item, index) => {
								// 尝试多种可能的字段名
								const medicineName = item.name || item.drugname || item.drug_name || item.medicinename || `药品${index + 1}`;
								const category = item.category || item.type || item.drugtype || item.classification || '药品';
								const usage = item.usage || item.dosage || item.method || '用法';
								const indication = item.indication || item.description || item.effect || item.function || '适应症';
								
								return {
									id: String(item.id || item.drugid || `med_${index}`),
									name: medicineName,
									type: 'medicine',
									description: `${category} | ${usage} | ${indication}`,
									image: item.image || item.drugimage || item.picture,
									price: item.price ? `¥${item.price}` : '价格面议',
								};
							});
						allResults.push(...medicineResults);
						console.log('处理后的药品结果:', medicineResults);
					} else {
						console.log('药品API返回空数据');
						// 不设置错误，只是没有找到相关药品
					}
				} catch (e) {
					console.warn('药品搜索失败:', e);
					console.log('错误详情:', {
						message: e.message,
						status: e.response?.status,
						statusText: e.response?.statusText,
						url: e.config?.url,
						params: e.config?.params
					});
					
					// 药品搜索失败时不显示错误提示，静默处理
					// 这样用户只会看到医生搜索结果，体验更好
				}
			}

			console.log('最终搜索结果:', allResults);
			setResults(allResults);
		} catch (e) {
			console.error('搜索失败:', e);
			setError('搜索失败，请稍后重试');
		} finally {
			setLoading(false);
		}
	};

	const handleResultClick = (r: SearchResult) => {
		if (r.type === 'doctor') {
			navigate(`/doctor/${r.id}`, {
				state: { doctorName: r.name, doctorDescription: r.description },
			});
			return;
		}
		
		if (r.type === 'hospital') {
			navigate(`/hospital/${r.id}`, {
				state: { hospitalName: r.name, hospitalDescription: r.description },
			});
			return;
		}
		
		if (r.type === 'medicine') {
			navigate(`/medicine/${r.id}`, {
				state: { medicineName: r.name, medicineDescription: r.description },
			});
			return;
		}
	};

	const getTypeIcon = (type: string) => {
		switch (type) {
			case 'doctor':
				return <User size={16} className="text-blue-600" />;
			case 'hospital':
				return <Building2 size={16} className="text-green-600" />;
			case 'medicine':
				return <Pill size={16} className="text-purple-600" />;
			default:
				return <Search size={16} className="text-gray-600" />;
		}
	};

	const getTypeLabel = (type: string) => {
		switch (type) {
			case 'doctor':
				return '医生';
			case 'hospital':
				return '医院';
			case 'medicine':
				return '药品';
			default:
				return '未知';
		}
	};

	const getTypeColor = (type: string) => {
		switch (type) {
			case 'doctor':
				return 'bg-blue-100 text-blue-700';
			case 'hospital':
				return 'bg-green-100 text-green-700';
			case 'medicine':
				return 'bg-purple-100 text-purple-700';
			default:
				return 'bg-gray-100 text-gray-700';
		}
	};

	const handleTabChange = (tab: SearchTab) => {
		console.log('切换标签:', tab, '当前搜索词:', value);
		setActiveTab(tab);
		setError(null); // 重置错误状态
		// 只有在有搜索词的情况下才重新搜索
		if (value.trim()) {
			// 清空之前的结果，重新搜索
			setResults([]);
			setLoading(true);
			// 延迟一点执行搜索，确保状态更新完成
			setTimeout(() => {
				doSearch();
			}, 100);
		}
	};



	return (
		<div className="min-h-screen bg-white flex flex-col">
			{/* 顶部 */}
			<div className="px-4 py-3 border-b border-gray-100 flex items-center space-x-3">
				<button onClick={() => navigate(-1)} className="p-2 rounded hover:bg-gray-100">
					<ArrowLeft size={20} />
				</button>
				<div className="relative flex-1">
					<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
					<input
						type="text"
						value={value}
						onChange={(e) => setValue(e.target.value)}
						onKeyDown={(e) => e.key === 'Enter' && doSearch()}
						placeholder="搜索医生、药品"
						className="w-full pl-10 pr-20 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
					/>
					<button
						onClick={() => doSearch()}
						className="absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1.5 bg-primary-500 text-white rounded-lg text-sm hover:bg-primary-600"
					>
						搜索
					</button>
				</div>
			</div>

			{/* 分类标签 */}
			<div className="px-4 py-3 border-b border-gray-100">
				<div className="flex space-x-6 overflow-x-auto">
					{[
						{ key: 'comprehensive', label: '综合' },
						{ key: 'doctor', label: '医生' },
						{ key: 'hospital', label: '医院' },
						{ key: 'medicine', label: '药品' },
					].map((tab) => (
						<button
							key={tab.key}
							onClick={() => handleTabChange(tab.key as SearchTab)}
							className={`flex-shrink-0 pb-2 px-1 text-sm font-medium transition-colors ${
								activeTab === tab.key
									? 'text-primary-600 border-b-2 border-primary-600'
									: 'text-gray-500 hover:text-gray-700'
							}`}
						>
							{tab.label}
						</button>
					))}
				</div>
				

				
				{/* 错误提示 */}
				{error && (
					<div className="mt-2 p-2 bg-red-50 border border-red-200 rounded-lg">
						<div className="flex items-center justify-between text-red-800 text-xs">
							<div className="flex items-center">
								<svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
									<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
								</svg>
								{error}
							</div>
							<button 
								onClick={() => setError(null)}
								className="text-red-600 hover:text-red-800"
							>
								×
							</button>
						</div>
					</div>
				)}
			</div>

			{/* 历史 */}
			<div className="p-4">
				<div className="flex items-center justify-between mb-3">
					<h3 className="text-base font-semibold text-gray-900">搜索记录</h3>
					<button onClick={() => dispatch(clearHistory())} className="p-2 text-gray-500 hover:text-gray-700">
						<Trash2 size={18} />
					</button>
				</div>

				{history.length === 0 ? (
					<p className="text-sm text-gray-400">暂无记录</p>
				) : (
					<div className="flex flex-wrap gap-2 mb-4">
						{history.map((item) => (
							<div key={item} className="flex items-center bg-gray-100 rounded-full pl-3">
								<button
									onClick={() => {
									setValue(item);
									doSearch(item);
								}}
									className="text-sm text-gray-700 py-1"
								>
									{item}
								</button>
								<button
									onClick={() => dispatch(removeHistory(item))}
									className="px-2 py-1 text-gray-400 hover:text-gray-600"
								>
									×
								</button>
							</div>
						))}
					</div>
				)}

				{/* 结果 */}
				<div>
					{loading ? (
						<div className="py-8 text-center text-gray-500">
							<div className="w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
							搜索中...
						</div>
					) : error ? (
						<div className="py-8 text-center text-red-500">{error}</div>
					) : results.length === 0 ? (
						<div className="py-8 text-center text-gray-400">没有搜索结果</div>
					) : (
						<div className="space-y-4">
							{/* 医生结果 */}
							{(activeTab === 'comprehensive' || activeTab === 'doctor') && results.filter(r => r.type === 'doctor').length > 0 && (
								<div>
									<div className="flex items-center justify-between mb-3">
										<h3 className="text-base font-semibold text-gray-900">相关医生</h3>
										<button className="text-blue-600 text-sm hover:text-blue-700">查看更多&gt;</button>
									</div>
									<div className="space-y-3">
										{results.filter(r => r.type === 'doctor').map((r) => (
											<div key={r.id} className="bg-white rounded-lg border border-gray-200 p-4">
												<div className="flex items-start space-x-3">
													{r.image && r.image.startsWith('http') ? (
														<img 
															src={r.image} 
															alt={r.name}
															className="w-16 h-16 rounded-full object-cover"
														/>
													) : (
														<div className="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center">
															<span className="text-lg font-semibold text-blue-600">
																{r.name.charAt(0)}
															</span>
														</div>
													)}
													<div className="flex-1">
														<div className="flex items-center space-x-2 mb-2">
															<h4 className="text-base font-medium text-gray-900">{r.name}</h4>
															<span className="text-sm text-gray-600">{r.author}</span>
														</div>
														<button className="px-3 py-1 bg-blue-100 text-blue-700 text-xs rounded-full mb-2">
															图文咨询
														</button>
														<p className="text-sm text-gray-600 mb-2">{r.description}</p>
														<div className="text-xs text-gray-500 mb-2">
															好评率{r.rating} | 锦旗2 | 浏览人次 {r.views}
														</div>
														<div className="text-sm text-red-600 font-medium">{r.price}</div>
														<button className="mt-2 px-4 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700">
															问医生
														</button>
													</div>
												</div>
											</div>
										))}
									</div>
								</div>
							)}

							{/* 医院结果 */}
							{(activeTab === 'comprehensive' || activeTab === 'hospital') && results.filter(r => r.type === 'hospital').length > 0 && (
								<div>
									<div className="flex items-center justify-between mb-3">
										<h3 className="text-base font-semibold text-gray-900">相关医院</h3>
										<button className="text-blue-600 text-sm hover:text-blue-700">查看更多&gt;</button>
									</div>
									<div className="space-y-3">
										{results.filter(r => r.type === 'hospital').map((r) => (
											<div key={r.id} className="bg-white rounded-lg border border-gray-200 p-4">
												<div className="flex items-start space-x-3">
													{r.image && r.image.startsWith('http') ? (
														<img 
															src={r.image} 
															alt={r.name}
															className="w-16 h-16 rounded-lg object-cover"
														/>
													) : (
														<div className="w-16 h-16 rounded-lg bg-green-100 flex items-center justify-center">
															<Building2 size={24} className="text-green-600" />
														</div>
													)}
													<div className="flex-1">
														<div className="flex items-center space-x-2 mb-2">
															<h4 className="text-base font-medium text-gray-900">{r.name}</h4>
															<span className="text-sm text-gray-600">{r.author}</span>
														</div>
														<p className="text-sm text-gray-600 mb-2">{r.description}</p>
														<div className="text-xs text-gray-500 mb-2">
															评分 {r.rating} | 浏览人次 {r.views}
														</div>
														<button 
															onClick={() => handleResultClick(r)}
															className="px-4 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700"
														>
															查看详情
														</button>
													</div>
												</div>
											</div>
										))}
									</div>
								</div>
							)}

							{/* 药品结果 */}
							{(activeTab === 'comprehensive' || activeTab === 'medicine') && results.filter(r => r.type === 'medicine').length > 0 && (
								<div>
									<div className="flex items-center justify-between mb-3">
										<h3 className="text-base font-semibold text-gray-900">相关药品</h3>
										<button className="text-blue-600 text-sm hover:text-blue-700">查看更多&gt;</button>
									</div>
									<div className="space-y-3">
										{results.filter(r => r.type === 'medicine').map((r) => (
											<div key={r.id} className="bg-white rounded-lg border border-gray-200 p-4">
												<div className="flex items-start space-x-3">
													<div className="w-16 h-16 rounded-full bg-purple-100 flex items-center justify-center">
														<Pill size={24} className="text-purple-600" />
													</div>
													<div className="flex-1">
														<h4 className="text-base font-medium text-gray-900 mb-2">{r.name}</h4>
														<p className="text-sm text-gray-600 mb-2">{r.description}</p>
														<div className="flex items-center justify-between">
															<span className="text-sm text-red-600 font-medium">{r.price}</span>
															<button 
																onClick={() => handleResultClick(r)}
																className="px-4 py-1 bg-purple-600 text-white text-sm rounded hover:bg-purple-700"
															>
																查看详情
															</button>
														</div>
													</div>
												</div>
											</div>
										))}
									</div>
								</div>
							)}

							{/* 其他类型结果 - 当选择综合标签时显示 */}
							{activeTab === 'comprehensive' && results.filter(r => !['doctor', 'hospital', 'medicine'].includes(r.type)).length > 0 && (
								<div className="divide-y divide-gray-100 bg-white rounded-lg border border-gray-100 overflow-hidden">
									{results.filter(r => !['doctor', 'hospital', 'medicine'].includes(r.type)).map((r) => (
										<button
											key={r.id}
											onClick={() => handleResultClick(r)}
											className="w-full text-left px-4 py-3 hover:bg-gray-50"
										>
											<div className="flex items-start gap-3">
												<div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center mt-0.5">
													{getTypeIcon(r.type)}
												</div>
												<div className="flex-1 min-w-0">
													<div className="flex items-center gap-2">
														<span className="text-sm font-medium text-gray-900 truncate">{r.name}</span>
														<span className={`text-xs px-2 py-0.5 rounded-full ${getTypeColor(r.type)}`}>
															{getTypeLabel(r.type)}
														</span>
													</div>
													{r.description && (
														<p className="text-xs text-gray-500 mt-1 line-clamp-2">{r.description}</p>
													)}
												</div>
											</div>
										</button>
									))}
								</div>
							)}
						</div>
					)}
				</div>
			</div>
		</div>
	);
}